/**
 * Created by Administrator on 2017/5/9.
 */
!(function($){
    var update = {
        userId: $.fn.cookie('userId'),
        isLogin: $.fn.cookie('isLogin'),
        init:function(){
            this.loadInfo();
            this.typeChange();
            this.getCat2Data();
            this.getCatData();
            this.uploadImg();
            this.delImg();
            this.update();
            this.defaultLoadType();
        },
        defaultLoadType:function(){
            setTimeout(function(){
                var typeId = $('#publish_type').val();

                if(typeId==1){
                    $('#getCatsbox').show();
                    $('#get2Catsbox').hide();
                }
                if(typeId==2){
                    $('#getCatsbox').hide();
                    $('#get2Catsbox').show();
                }
                if(typeId==3){
                    $('#getCatsbox').hide();
                    $('#get2Catsbox').hide();
                    $('div.pricebox').hide();
                }else{
                    $('div.pricebox').show();
                }
            },300)
        },
        typeChange:function(){
            var self = this;
            $('.product_type li').on('click',function(){
                $(this).addClass('selected').siblings().removeClass('selected');
                var typeId = $(this).attr('type');
                $('#publish_type').val(typeId);
                if(typeId==1){
                    $('#getCatsbox').show();
                    $('#get2Catsbox').hide();
                    self.getCatData();
                }
                if(typeId==2){
                    $('#getCatsbox').hide();
                    $('#get2Catsbox').show();
                    self.getCat2Data();
                }
                if(typeId==3){
                    $('#getCatsbox').hide();
                    $('#get2Catsbox').hide();
                    $('div.pricebox').hide();
                }else{
                    $('div.pricebox').show();
                }
            })
        },
        getCat2Data:function(){
            var param = {type:2};
            var arrs = [];
            $.ajax({
                url: API_URL + GET_CATEGORYS_URL,
                type: 'get',
                dataType: 'jsonp',
                data:param,
                success: function (data) {
                    //分类拼接
                    var datas= data.result;
                    var json = {};
                    for(var i = 0;i<datas.length;i++){
                        json = {title:datas[i].name,value:datas[i].id};
                        arrs.push(json);
                    }
                    $("#get2Cats").select({
                        title: "选择分类",
                        items: arrs,
                        onChange: function(d) {
                            $('#type_categoryId').val(d.values);
                            $('#get2Cats .weui_cell_ft').html(d.titles);
                        }
                    });

                }
            });
        },
        getCatData : function(){
            var param = {type:1};
            var arrs = [];
            $.ajax({
                url: API_URL + GET_CATEGORYS_URL,
                type: 'get',
                dataType: 'jsonp',
                data:param,
                success: function (data) {
                    //分类拼接
                    var datas= data.result;
                    var json = {};
                    for(var i = 0;i<datas.length;i++){
                        json = {title:datas[i].name,value:datas[i].id};
                        arrs.push(json);
                    }
                    $("#getCats").select({
                        title: "选择分类",
                        items: arrs,
                        onChange: function(d) {
                            $('#type_categoryId').val(d.values);
                            $('#getCats .weui_cell_ft').html(d.titles);
                        }
                    });

                }
            });
        },
        uploadImg:function(){
            var f2 = document.querySelector('#addimgurls');
            var idsList =  JSON.parse( $('#idList').val() || '[]' );

            f2.onchange = function (e) {
                lrz(this.files[0],{width:750}).then(function (rst) {
                        var params = {
                            type: 2,
                            file: rst.base64,
                            name: rst.origin.name,
                            fileLength: rst.base64.length
                        };
                        $.ajax({
                            type: "POST",
                            url: API_URL+IMG_UPLOAD,
                            data: params,
                            dataType: "json",
                            beforeSend: function (XMLHttpRequest) {
                                // showLoader();
                            },
                            success: function (data) {
                                if(data.ok==true){
                                    $('#imgs').append('<li data-id='+data.result.id+' class="weui_uploader_file weui_uploader_status" class="weui_uploader_file" style="background-image:url('+data.result.smallUrl+')"><div class="weui_uploader_status_content"><i class="icon icon-img-del"></i></div></li>');
                                    var len = $('#imgs li').length;
                                    $('#imgsCount').html(len+'/4');
                                    if(len==4){
                                        $('#filed').hide();
                                        return;
                                    }
                                    if(len>4){
                                        $.toptips('图片数量不能超过4张！','info');
                                        return;
                                    }
                                    else{
                                        $('#filed').show();
                                    }
                                    idsList.push(data.result.id);
                                    $('#imageIds').val(JSON.stringify(idsList));
                                }
                            },
                            complete: function (XMLHttpRequest, textStatus) {
                                // hideLoader();
                            },
                            error:function (XMLHttpRequest, textStatus, errorThrown) {
                                $.toptips("上传失败");
                            }
                        });
                        return rst;
                    })
                    .catch(function (err) {
                        $.toptips(err);
                    })
            }
        },
        delImg:function(){
            $('#imgs').delegate('.icon-img-del','click',function(){
                var delimg = $(this).closest('li');
                var delId = $(this).closest('li').data('id');
                $.confirm('您确定删除吗？','确认删除？',function(){
                    var idsList =  JSON.parse($('#imageIds').val());
                    idsList.remove(delId);//从数组中删除项
                    $('#imageIds').val(JSON.stringify(idsList));
                    delimg.remove();
                    var len = $('#imgs li').length;
                    $('#imgsCount').html(len+'/4');
                    if(len<4){
                        $('#filed').show();
                    }
                },function(){
                    $.toast('取消操作', 'cancel');
                })
            });
        },
        verifySubmit:function(){
            var messages = $('#messages').val();
            var uploadImgs = $('#imageIds').val();
            var typeCategoryId = $('#type_categoryId').val();
            var price = $('#price').val();
            var typeId = $('ul.product_type li.selected').attr('type');
            if(typeId==3){
                if(uploadImgs=='' && uploadImgs == []){
                    $.toptips('请添加图片！','info');
                    return false;
                }
                if(messages == ''){
                    $.toptips('请填写信息！','info');
                    return false;
                }
            }else{
                if(uploadImgs==''){
                    $.toptips('请添加图片！','info');
                    return false;
                }
                if(typeCategoryId==''){
                    $.toptips('请选择类目！','info');
                    return false;
                }
                if(messages == ''){
                    $.toptips('请填写信息！','info');
                    return false;
                }
                if(price==''){
                    $.toptips('请填写价格！','info');
                    return false;
                }
            }
            return true;
        },
        loadInfo:function(){
            var self = this;
            var id = GetQueryString('id');
            var imgArrs = [];
            $.ajax({
                url:API_URL+GET_SINGLE_PRO_URL,
                type:"post",
                dataType:'jsonp',
                data:{id:id},
                success:function(data){
                    if(data.ok=true){
                        var datas = data.result;
                        var imglen = datas.images.length;
                        var type = datas.type;
                        var categoryId = datas.categoryId;
                        $('ul.product_type li[type="'+type+'"]').addClass('selected').siblings().removeClass('selected');
                        $('#messages').val(datas.desc);
                        $('#price').val(datas.price);
                        var imgtpl = '';
                        if(imglen>=4){
                            $('#filed').hide();
                        }else{
                            $('#filed').show();
                        }
                        var getText = $('#getCats .weui_cell_ft');
                        var getText2 = $('#get2Cats .weui_cell_ft');
                        if(type==1){
                            switch (categoryId){
                                case 1:
                                    getText.html('农畜牧品');
                                    break;
                                case 2:
                                    getText.html('农用机械');
                                    break;
                                case 4:
                                    getText.html('种子肥料');
                                    break;
                                case 3:
                                    getText.html('蔬菜水果');
                                    break;
                            }
                        }
                        if(type==2){
                            switch (categoryId){
                                case 5:
                                    getText2.html('房屋买卖');
                                    break;
                                case 6:
                                    getText2.html('二手买卖');
                                    break;
                                case 7:
                                    getText2.html('家电维修');
                                    break;

                            }
                        }
                        $('#imgsCount').html(imglen+'/4');
                        for(var i = 0;i<datas.images.length;i++){
                            imgtpl += '<li data-id="'+datas.images[i].id+'" class="weui_uploader_file weui_uploader_status" style="background-image:url('+datas.images[i].smallUrl+')">' +
                                '<div class="weui_uploader_status_content"><i class="icon icon-img-del"></i></div>'+
                                '</li>';
                            imgArrs.push(datas.images[i].id);
                        }
                        $('#imageIds').val(JSON.stringify(imgArrs));
                        $('#id').val(datas.id);
                        $('#imgs').html(imgtpl);
                        $('#categoryId').val(datas.categoryId);
                        $('#publish_type').val(datas.type);
                        if(self.verifySubmit()==false){
                            $('#btn-publish').addClass('disabled');
                        }else{
                            $('#btn-publish').removeClass('disabled');
                        }
                    }
                }

            })
        },
        update:function(){
            var self = this;
            $('#btn-publish').on('click',function(){
                var typeId = $('ul.product_type li.selected').attr('type');
                var params  = {};
                var imgIds = JSON.parse($("#imageIds").val());
                if(typeId==3){
                    params = {
                        id:$('#id').val(),
                        userId:self.userId,
                        message:$('#messages').val(),
                        imageId:imgIds
                    };
                    if(self.verifySubmit()){
                        $('#btn-publish').removeClass('disabled');
                        $.ajax({
                            url:API_URL+PUBLISH_FEEDBACKS_URL,
                            type:'post',
                            dataType:'jsonp',
                            data:params,
                            success:function(data){
                                if(data.ok==true){
                                    $.toast('更新成功!');
                                    setTimeout(function(){
                                        window.location.href='my_products_list.html'
                                    },1000)
                                }
                            }
                        })
                    }else{
                        $('#btn-publish').addClass('disabled');
                    }
                }else{
                    params = {
                        id:$('#id').val(),
                        userId:self.userId,
                        desc:$('#messages').val(),
                        imageId:imgIds,
                        type:$('#publish_type').val(),
                        categoryId:$('#categoryId').val(),
                        price:$('#price').val()
                    };
                    if(self.verifySubmit()){
                        $('#btn-publish').removeClass('disabled');
                        $.ajax({
                            url:API_URL+UPDATE_URL,
                            type:'post',
                            dataType:'jsonp',
                            data:params,
                            success:function(data){
                                if(data.ok==true){
                                    $.toast('更新成功!');
                                    setTimeout(function(){
                                        window.location.href='my_products_list.html'
                                    },1000)
                                }
                            }
                        });
                    }else{
                        $('#btn-publish').addClass('disabled');
                    }

                }
            });

        }
    }
    $(function(){
        update.init();
    })
})(Zepto);